
<template>
    <div class="login-container">
        <el-form :model="loginForm" status-icon :rules="rules" ref="loginForm" label-width="100px" class="login-loginForm">
  <el-form-item label="用户名" prop="username">
    <el-input type="text" v-model="loginForm.username" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item label="密码" prop="password">
    <el-input type="password" v-model="loginForm.password" autocomplete="off"></el-input>
  </el-form-item>
  <el-form-item label="验证码" prop="captcha">
    <el-input v-model.number="loginForm.captcha"></el-input>
  </el-form-item>
  <el-form-item>
    <el-button type="primary" @click="submitForm('loginForm')">提交</el-button>
    <el-button @click="resetForm('loginForm')">重置</el-button>
  </el-form-item>
</el-form>
    </div>
</template>
<script>
//校验验证码
  var validateCpatcha = (rule, value, callback) => {
        if (!value) {
          return callback(new Error('年龄不能为空'));
        }
        setTimeout(() => {
          if (!Number.isInteger(value)) {
            callback(new Error('请输入数字值'));
          } else {
            if (value < 18) {
              callback(new Error('必须年满18岁'));
            } else {
              callback();
            }
          }
        }, 1000);
      };
      //校验用户名
      var validateUsername = (rule, value, callback) => {
        //value就是输入框的内容
        //callback回调函数，如果不传参数，表示校验通过，如果传递参数，表示校验不通过
        var reg=/^[0-9A-Za-z_]{6,20}$/;
        //由数字、字母、下划线组成的6-20位
        if (!reg.test(value)) {
          callback("由数字、字母、下划线组成的6-20位");
        } else {
          callback();
        }
      };
      //校验密码
      var validatePassword = (rule, value, callback) => {
        if (value === '') {
          callback(new Error('请再次输入密码'));
        } else if (value !== this.loginForm.username) {
          callback(new Error('两次输入密码不一致!'));
        } else {
          callback();
        }
      };
  export default {
    name:"login",
    data() {
      return {
        loginForm: {
          username: '',
          password: '',
          captcha: ''
        },
        rules: {
          username: [
            { validator: validateUsername, trigger: 'blur' }
          ],
          password: [
            { validator: validatePassword, trigger: 'blur' }
          ],
          captcha: [
            { validator: validateCpatcha, trigger: 'blur' }
          ]
        }
      };
    },
    methods: {
      submitForm(formName) {
        this.$refs[formName].validate((valid) => {
          if (valid) {
            alert('submit!');
          } else {
            console.log('error submit!!');
            return false;
          }
        });
      },
      resetForm(formName) {
        this.$refs[formName].resetFields();
      }
    }
  }